package com.example.myapplication.base;


import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import java.lang.ref.WeakReference;

public class BaseViewModel extends AndroidViewModel implements IBaseViewModel {

    private boolean hasCleared = false;

    private WeakReference<LifecycleOwner> lifecycle;

    public BaseViewModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 注入Lifecycle生命周期
     * @param lifecycleOwner Activity或Fragment
     */
    public void injectLifecycleProvider(LifecycleOwner lifecycleOwner) {
        this.lifecycle = new WeakReference<>(lifecycleOwner);
    }

    /**
     * 获取注入的Lifecycle引用对象
     * @return 返回Lifecycle引用对象，如果对象被清除，会返回null
     */
    public LifecycleOwner getLifecycleProvider() {
        return this.lifecycle.get();
    }

    @Override
    public void onAny(LifecycleOwner owner, Lifecycle.Event event) {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onStart() {

    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void onDestroy() {
        if (!hasCleared) {
            onCleared();
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        hasCleared = true;
    }
}
